package com.ziyun.erp.modules.goodsCraftPrice.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ziyun.erp.modules.goods.entity.GoodsOptionEntity;
import com.ziyun.erp.modules.goods.entity.GoodsTemplateEntity;
import com.ziyun.erp.modules.goods.service.GoodsOptionService;
import com.ziyun.erp.modules.goods.service.GoodsTemplateService;
import com.ziyun.erp.modules.goodsCraftPrice.dao.GoodsCraftPriceDao;
import com.ziyun.erp.modules.goodsCraftPrice.dto.GoodsTemplateOptionDto;
import com.ziyun.erp.modules.goodsCraftPrice.entity.GoodsCraftPriceEntity;
import com.ziyun.erp.modules.goodsCraftPrice.service.GoodsCraftPriceService;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service("goodsCraftPriceService")
public class GoodsCraftPriceServiceImpl extends ServiceImpl<GoodsCraftPriceDao, GoodsCraftPriceEntity> implements GoodsCraftPriceService {
    @Autowired
    private GoodsTemplateService goodsTemplateService;

    @Autowired
    private GoodsOptionService goodsOptionService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<GoodsCraftPriceEntity> page = this.selectPage(
                new Query<GoodsCraftPriceEntity>(params).getPage(),
                new EntityWrapper<GoodsCraftPriceEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询商家 已经配置价格的工艺
     *
     * @param sellerId
     * @return
     */
    @Override
    public Map<String, Object> getGoodsCraftPriceList(Long sellerId) {
        Map<String, Object> rsMap = new HashMap<String, Object>();

        // 先查询左侧table 关联的工艺
        List<Map<String, Object>> goodsCraftList = this.baseMapper.selectGoodsCraftList(sellerId);

        //再查询右侧 工艺配价列表
        List<GoodsCraftPriceEntity> goodsCraftPriceList = this.baseMapper.selectGoodsCraftPrice(sellerId);

        rsMap.put("goodsCraftList", goodsCraftList);
        rsMap.put("goodsCraftPriceList", goodsCraftPriceList);
        return rsMap;
    }

    /**
     * 查询商家 已经配置基础商品模板价格的工艺
     *
     * @param sellerId
     * @return
     */
    @Override
    public Map<String, Object> getGoodsTemplateCraftPriceList(Long sellerId) {
        Map<String, Object> rsMap = new HashMap<String, Object>();

        // 先查询左侧table 关联的工艺
        List<Map<String, Object>> goodsCraftList = this.baseMapper.selectGoodsCraftList(sellerId);

        // 查询中间table 关联的模板
        List<GoodsTemplateEntity> goodsTemplateList = this.baseMapper.selectGoodsTemplateList(sellerId);

        //再查询右侧 工艺配价列表
        List<GoodsCraftPriceEntity> goodsCraftPriceList = this.baseMapper.selectGoodsCraftPrice(sellerId);

        rsMap.put("goodsCraftList", goodsCraftList);
        rsMap.put("goodsTemplateList", goodsTemplateList);
        rsMap.put("goodsCraftPriceList", goodsCraftPriceList);
        return rsMap;
    }

    @Override
    public Map<String, Object> getGoodsTemplateCraftPriceWindowList(Map<String, Object> params) {
        String attributeIds = params.get("attributeIds").toString();
        Integer templateId = Integer.parseInt(params.get("templateId").toString());
        params.put("attributeIds", attributeIds.split(","));

        Map<String, Object> rsMap = new HashMap<String, Object>();
        // 先查询左侧table 关联的工艺
        List<Map<String, Object>> goodsCraftList = this.baseMapper.selectGoodsCraftOrPriceList(params);

        //查询模板信息
        GoodsTemplateEntity goodsTemplateEntity = this.goodsTemplateService.selectById(templateId);

        //再查询右侧 工艺配价列表
        List<GoodsCraftPriceEntity> goodsCraftPriceList = this.baseMapper.selectGoodsCraftPriceByParams(params);

        rsMap.put("goodsCraftList", goodsCraftList);
        rsMap.put("goodsTemplate", goodsTemplateEntity);
        rsMap.put("goodsCraftPriceList", goodsCraftPriceList);
        return rsMap;
    }


    /**
     * 查询工艺价格选项
     *
     * @param parasMap
     * @return
     */
    @Override
    public List<GoodsCraftPriceEntity> getGoodsCraftOptionPriceList(Map<String, Object> parasMap) {
        List<GoodsCraftPriceEntity> goodsCraftPriceList = this.baseMapper.selectGoodsCraftOptionPriceList(parasMap);
        return goodsCraftPriceList;
    }

    /**
     * 根据工艺id 商户id删除工艺报价
     *
     * @param parasMap
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByAttributeId(Map<String, Object> parasMap) {
        this.baseMapper.deleteByAttributeId(parasMap);
    }

    /**
     * 根据工艺ids 删除报价
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(List<Integer> ids) {
        this.baseMapper.deleteBatchIds(ids);
    }


    /**
     * 保存基础商品工艺价格
     *
     * @param goodsCraftPriceList
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(List<GoodsCraftPriceEntity> goodsCraftPriceList, String userName, Long sellerId) {
        //遍历组装数组
        Date date = new Date();

        List<GoodsCraftPriceEntity> updateList = new ArrayList<GoodsCraftPriceEntity>();
        List<GoodsCraftPriceEntity> insertList = new ArrayList<GoodsCraftPriceEntity>();
        List<Integer> templateList = new ArrayList<>();
        List<Long> optionIdList = new ArrayList<>();
        List<Integer> influenceOptionIdList = new ArrayList<>();
        for (GoodsCraftPriceEntity goodsCraftPriceEntity : goodsCraftPriceList) {
            // 判断是新增还是修改
            if (goodsCraftPriceEntity.getCraftPriceId() != null) {
                updateList.add(goodsCraftPriceEntity);
            } else {
                //新增数据
                templateList.add(goodsCraftPriceEntity.getTemplateId());
                optionIdList.add(goodsCraftPriceEntity.getOptionId());
                influenceOptionIdList.add(goodsCraftPriceEntity.getInfluenceId());
                goodsCraftPriceEntity.setOptionOrigin("standard_craft");
                goodsCraftPriceEntity.setSellerId(sellerId);
                goodsCraftPriceEntity.setCreateName(userName);
                goodsCraftPriceEntity.setCreateTime(date);
                insertList.add(goodsCraftPriceEntity);
            }

        }
        if (insertList.size() > 0) {
            // 校验重复
            Map<String,Object> queryMap = new HashMap<String,Object>();
            List<Map> ids = new ArrayList<>();
            for (int i=0;i< optionIdList.size();i ++ ){
                Map<String,Object> map = new HashMap();
                map.put("templateId", templateList.get(i));
                map.put("optionId", optionIdList.get(i));
                map.put("influenceId", influenceOptionIdList.get(i));
                ids.add(map);
            }
            queryMap.put("ids", ids);
            queryMap.put("optionOrigin", "standard_craft");
            queryMap.put("sellerId", sellerId);

            int count = this.baseMapper.selectCountByMap(queryMap);
           /* int count = this.selectCount(new EntityWrapper<GoodsCraftPriceEntity>()
                    .eq("option_origin", "standard_craft")
                    .eq("seller_id",sellerId)
                    .in("template_id", templateList)
                    .in("option_id", optionIdList)
                    .in(influenceOptionIdList.size()>0,"influence_id",influenceOptionIdList)
            );*/
            if (count >0){
                throw new RRException("当前工艺选项,存在已配价选项,请刷新页面重试 !");
            }

            this.insertBatch(insertList);
        }

        if (updateList.size() > 0) {
            this.updateBatchById(updateList);
        }

    }

    /**
     * 通过工艺id 查询该工艺所在模板配置的工艺选项价格
     *
     * @param goodsTemplateOptionDto
     * @return
     */
    @Override
    public List<GoodsCraftPriceEntity> getGoodsTemplateOptionList(GoodsTemplateOptionDto goodsTemplateOptionDto) {
        // 当前工艺id
        Integer attributeId = goodsTemplateOptionDto.getAttributeId();
        // 当前模板
        GoodsTemplateEntity goodsTemplate = goodsTemplateOptionDto.getGoodsTemplate();

        //解析当前模板 选项
        String optionJson = goodsTemplate.getOptionJson();
        if (StringUtil.isEmpty(optionJson)) {
            throw new RRException("数据模板异常!");
        }

        List<Object> optionList = new ArrayList<>(); // 选项列表

        JSONArray jsonArrayOption = JSONArray.parseArray(optionJson);
        // 循环jsonArray 取出当前工艺选项
        for (int i = 0; i < jsonArrayOption.size(); i++) {
            JSONObject jsonObject = jsonArrayOption.getJSONObject(i);
            // 取出当前工艺选项
            if (jsonObject.getInteger("attributeId").equals(attributeId)) {
                optionList.addAll(jsonObject.getJSONArray("optionId"));
                break;
            }
        }

        // 解析 influence_craft_ids
        List<Object> influenceAttributeIdList = new ArrayList<Object>(); //受影响普通属性
        String influenceCraftIds = goodsTemplate.getInfluenceCraftIds();
        if (StringUtil.isNotEmpty(influenceCraftIds)){
            JSONArray jsonArrayInfluenceCraftIds = JSONArray.parseArray(influenceCraftIds);
            // 循环取出 当前受影响工艺的属性选项
            for (int i=0; i< jsonArrayInfluenceCraftIds.size(); i++){
                JSONObject influenceCraftId = jsonArrayInfluenceCraftIds.getJSONObject(i);
                if (influenceCraftId.getInteger("craftId").equals(attributeId)){
                    if(influenceCraftId.getJSONArray("attributeIds").size()>0){
                        // 存放受影响属性
                        influenceAttributeIdList.addAll(influenceCraftId.getJSONArray("attributeIds"));
                    }
                    break;
                }
            }
        }
        //受影响普通属性 选项
        List<Object> influenceOptionList = new ArrayList<Object>();
        // 再次循环 jsonArrayOption 找出 受影响属性选项
        if (influenceAttributeIdList.size() >0){
            for (int i = 0; i < jsonArrayOption.size(); i++) {
                JSONObject jsonObject = jsonArrayOption.getJSONObject(i);
                // 循环 influenceAttributeIdList
                for (Object influenceAttributeId : influenceAttributeIdList){
                    if (jsonObject.getInteger("attributeId").equals(influenceAttributeId)) {
                        influenceOptionList.addAll(jsonObject.getJSONArray("optionId"));
                    }
                }
            }
        }

        Map<String,Object> queryParam = new HashMap<String,Object> ();
        queryParam.put("templateId",goodsTemplate.getTemplateId());
        queryParam.put("optionList",optionList);
        if(influenceOptionList.size() >0){
            //再取 自定义受影响ID
           List<Object> optionIdList = this.goodsOptionService.selectObjs(new EntityWrapper<GoodsOptionEntity>()
                    .setSqlSelect("option_id")
                    .eq("seller_id",goodsTemplateOptionDto.getSellerId()));
            if(optionIdList.size() >0){
                influenceOptionList.addAll(optionIdList);
            }
            queryParam.put("influenceOptionList",influenceOptionList);
        }
        queryParam.put("sellerId", goodsTemplateOptionDto.getSellerId());

        // 去数据库查询最终展示数据
        List<GoodsCraftPriceEntity> goodsCraftPriceList = this.baseMapper.selectGoodsCraftTemplateOptionPriceList(queryParam);


        return goodsCraftPriceList;
    }


    /*============ 以下为印刷商品工艺价格相关信息 ====================*/

    /**
     * 查询印刷商品价格
     *
     * @param sellerId
     * @return
     */
    @Override
    public Map<String, Object> getYinshuaGoodsCraftPriceList(Long sellerId) {
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("sellerId", sellerId);
        paramsMap.put("printType", "shangwuyinshua");
        paramsMap.put("attributeOrigin", "print");


        Map<String, Object> rsMap = new HashMap<String, Object>();
        // 先查询左侧table 关联的工艺
        List<Map<String, Object>> yinshuaGoodsCraftList = this.baseMapper.selectQuoteGoodsCraftList(paramsMap);

        //再查询右侧 工艺配价列表
        List<GoodsCraftPriceEntity> yinshuaGoodsCraftPriceList = this.baseMapper.selectQuoteGoodsCraftPrice(paramsMap);

        rsMap.put("yinshuaGoodsCraftList", yinshuaGoodsCraftList);
        rsMap.put("yinshuaGoodsCraftPriceList", yinshuaGoodsCraftPriceList);
        return rsMap;
    }

    /**
     * 查询报价工艺
     *
     * @param parasMap
     * @return
     */
    @Override
    public List<GoodsCraftPriceEntity> getQuoteGoodsCraftOptionPriceList(Map<String, Object> parasMap) {
        List<GoodsCraftPriceEntity> goodsCraftPriceList = this.baseMapper.selectQuoteGoodsCraftOptionPriceList(parasMap);
        return goodsCraftPriceList;
    }

    /*印刷工艺价格保存*/
    @Override
    public void saveYinshua(List<GoodsCraftPriceEntity> craftPriceList, String userName, Long sellerId) {

        Map<String, Object> rsMap = this.handleWebData(craftPriceList, userName, sellerId);

        List<GoodsCraftPriceEntity> updateList = (List<GoodsCraftPriceEntity>) rsMap.get("updateList");
        List<GoodsCraftPriceEntity> insertList = (List<GoodsCraftPriceEntity>) rsMap.get("insertList");

        if (insertList.size() > 0) {
            List<Long> optionList = new ArrayList<>();
            for(GoodsCraftPriceEntity temp :insertList){
                optionList.add(temp.getOptionId());
            }
            //校验重复
            int count = this.selectCount(new EntityWrapper<GoodsCraftPriceEntity>()
                    .eq("option_origin", "quote_craft")
                    .eq("seller_id",sellerId)
                    .in("option_id",optionList)
            );
            if (count >0){
                throw new RRException("当前工艺选项,存在已配价选项,请刷新页面重试 !");
            }
            this.insertBatch(insertList);
        }

        if (updateList.size() > 0) {
            this.updateBatchById(updateList);
        }
    }

    private Map<String, Object> handleWebData(List<GoodsCraftPriceEntity> craftPriceList, String userName, Long sellerId) {
        Map<String, Object> rsMap = new HashMap<String, Object>();
        //遍历组装数组
        Date date = new Date();

        List<GoodsCraftPriceEntity> updateList = new ArrayList<GoodsCraftPriceEntity>();
        List<GoodsCraftPriceEntity> insertList = new ArrayList<GoodsCraftPriceEntity>();
        for (GoodsCraftPriceEntity goodsCraftPriceEntity : craftPriceList) {
            // 判断是新增还是修改
            if (goodsCraftPriceEntity.getCraftPriceId() != null) {
                updateList.add(goodsCraftPriceEntity);
            } else {
                //新增数据
                goodsCraftPriceEntity.setOptionOrigin("quote_craft");
                goodsCraftPriceEntity.setSellerId(sellerId);
                goodsCraftPriceEntity.setCreateName(userName);
                goodsCraftPriceEntity.setCreateTime(date);
                insertList.add(goodsCraftPriceEntity);
            }
        }
        rsMap.put("updateList", updateList);
        rsMap.put("insertList", insertList);

        return rsMap;
    }

    /**
     * 根据属性id 删除印刷工艺价格
     *
     * @param parasMap
     */
    @Override
    public void deleteQuoteByAttributeId(Map<String, Object> parasMap) {

        this.baseMapper.deleteQuoteByAttributeId(parasMap);

    }


    /*============ 以下为印刷商品工艺价格相关信息 ====================*/

    /**
     * 获取快印工艺价格
     *
     * @param sellerId
     * @return
     */
    @Override
    public Map<String, Object> getKuaiyinGoodsCraftPriceList(Long sellerId) {
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("sellerId", sellerId);
        paramsMap.put("printType", "shumakuaiyin");
        paramsMap.put("attributeOrigin", "fast");

        Map<String, Object> rsMap = new HashMap<String, Object>();
        // 先查询左侧table 关联的工艺
        List<Map<String, Object>> kuaiyinGoodsCraftList = this.baseMapper.selectQuoteGoodsCraftList(paramsMap);

        //再查询右侧 工艺配价列表
        List<GoodsCraftPriceEntity> kuaiyinGoodsCraftPriceList = this.baseMapper.selectQuoteGoodsCraftPrice(paramsMap);

        rsMap.put("kuaiyinGoodsCraftList", kuaiyinGoodsCraftList);
        rsMap.put("kuaiyinGoodsCraftPriceList", kuaiyinGoodsCraftPriceList);
        return rsMap;
    }



    /**
     * 快印工艺价格保存
     *
     * @param craftPriceList
     * @param userName
     * @param sellerId
     */
    @Override
    public void saveKuaiyin(List<GoodsCraftPriceEntity> craftPriceList, String userName, Long sellerId) {
        //快印价格需要先判断选项与尺寸是否重复
        for (GoodsCraftPriceEntity goodsCraftPriceEntity : craftPriceList) {
            String optionName = this.isExist(goodsCraftPriceEntity, craftPriceList);
            if (StringUtils.isNotEmpty(optionName)) {
                throw new RRException("选项【" + optionName + "】存在相同尺寸!");
            }
        }

        Map<String, Object> rsMap = this.handleWebData(craftPriceList, userName, sellerId);

        List<GoodsCraftPriceEntity> updateList = (List<GoodsCraftPriceEntity>) rsMap.get("updateList");
        List<GoodsCraftPriceEntity> insertList = (List<GoodsCraftPriceEntity>) rsMap.get("insertList");

        if (insertList.size() > 0) {
            List<Long> optionList = new ArrayList<>();
            List<String> craftSizeList = new ArrayList<>();
            for(GoodsCraftPriceEntity temp :insertList){
                optionList.add(temp.getOptionId());
                if(temp.getCraftSize() !=null){
                    craftSizeList.add(temp.getCraftSize());
                }
            }
            //校验重复
            int count = this.selectCount(new EntityWrapper<GoodsCraftPriceEntity>()
                    .eq("option_origin", "quote_craft")
                    .eq("seller_id",sellerId)
                    .in("option_id",optionList)
                    .in(craftSizeList.size()>0,"craft_size",craftSizeList)
            );
            if (count >0){
                throw new RRException("当前工艺选项,存在已配价选项,请刷新页面重试 !");
            }
            this.insertBatch(insertList);
        }

        if (updateList.size() > 0) {
            this.updateBatchById(updateList);
        }

    }


    /**
     * 根据工艺与尺寸判断是否存在
     *
     * @param goodsCraftPriceEntity
     * @param craftPriceList
     * @return
     */
    private String isExist(GoodsCraftPriceEntity goodsCraftPriceEntity, List<GoodsCraftPriceEntity> craftPriceList) {
        String optionName = null;
        List<String> list = new ArrayList<>();
        for (GoodsCraftPriceEntity temp : craftPriceList) {
            if (temp.getOptionId().equals(goodsCraftPriceEntity.getOptionId())) {

                String tempCraftSize = temp.getCraftSize();
                String currentCraftSize = goodsCraftPriceEntity.getCraftSize();
                if (StringUtil.isEmpty(tempCraftSize) && StringUtil.isEmpty(currentCraftSize)) {
                    list.add(temp.getOptionName());
                }
                if (StringUtil.isNotEmpty(tempCraftSize) && StringUtil.isNotEmpty(currentCraftSize) && tempCraftSize.equals(currentCraftSize)) {
                    list.add(temp.getOptionName());
                }
            }
            if (list.size() > 1) {
                break;
            }
        }
        if (list.size() > 1) { //相同数量超过一个
            optionName = list.get(0);
        }
        return optionName;
    }

}
